import React, { useEffect, useState } from 'react';
import { Table, Input, Button, Tag, Space, Card, Row, Col, Select, Spin } from 'antd';
import { SearchOutlined, EditOutlined, EyeOutlined } from '@ant-design/icons';
import { Link } from 'react-router-dom';
import { useDispatch, useSelector } from 'react-redux';
import { fetchComments } from './commentSlice';
import { RootState } from '@/store';
import { Comment, CommentTag } from '@/types/comment';
import { getCommentTags} from '@/api/commentApi';

const { Option } = Select;
const { Search } = Input;

const CommentListPage: React.FC = () => {
  const dispatch = useDispatch();
  const { comments, loading, total } = useSelector((state: RootState) => state.comments);
  const [tags, setTags] = useState<CommentTag[]>([]);
  const [searchText, setSearchText] = useState('');
  const [selectedTag, setSelectedTag] = useState('');
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total,
  });

  // 获取标签列表
  useEffect(() => {
    const loadTags = async () => {
      try {
        const data = await getCommentTags();
        setTags(data.tags);
      } catch (error) {
        console.error('Failed to load tags:', error);
      }
    };
    loadTags();
  }, []);

  // 获取评论列表
  useEffect(() => {
    dispatch(fetchComments({
      page: pagination.current,
      pageSize: pagination.pageSize,
      keyword: searchText,
      tagId: selectedTag,
    }) as any);
  }, [dispatch, pagination, searchText, selectedTag]);

  // 处理分页变化
  const handleTableChange = (newPagination: any) => {
    setPagination({
      ...pagination,
      current: newPagination.current,
      pageSize: newPagination.pageSize,
    });
  };

  // 处理搜索
  const handleSearch = (value: string) => {
    setSearchText(value);
    setPagination({ ...pagination, current: 1 }); // 重置到第一页
  };

  // 处理标签筛选
  const handleTagChange = (value: string) => {
    setSelectedTag(value);
    setPagination({ ...pagination, current: 1 }); // 重置到第一页
  };

  // 表格列定义
  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: 80,
    },
    {
      title: '评论内容',
      dataIndex: 'content',
      key: 'content',
      ellipsis: true,
    },
    {
      title: '产品',
      dataIndex: 'productName',
      key: 'productName',
      width: 120,
    },
    {
      title: '用户',
      dataIndex: 'username',
      key: 'username',
      width: 100,
    },
    {
      title: '日期',
      dataIndex: 'createdAt',
      key: 'createdAt',
      width: 120,
    },
    {
      title: '标签',
      key: 'tags',
      render: (_: any, record: Comment) => (
        <Space size="small">
          {record.tags.map(tag => (
            <Tag key={tag.id} color={tag.color}>{tag.name}</Tag>
          ))}
        </Space>
      ),
    },
    {
      title: '操作',
      key: 'action',
      width: 120,
      render: (_: any, record: Comment) => (
        <Space size="middle">
          <Link to={`/comments/${record.id}`}>
            <EyeOutlined title="查看详情" />
          </Link>
          <Link to={`/comments/${record.id}/edit`}>
            <EditOutlined title="编辑标签" />
          </Link>
        </Space>
      ),
    },
  ];

  return (
    <Card>
      <Row gutter={[16, 16]} style={{ marginBottom: 16 }}>
        <Col xs={24} sm={12} lg={8}>
          <Search
            placeholder="搜索评论内容"
            allowClear
            enterButton={<SearchOutlined />}
            onSearch={handleSearch}
          />
        </Col>
        <Col xs={24} sm={12} lg={6}>
          <Select
            placeholder="选择标签筛选"
            style={{ width: '100%' }}
            allowClear
            onChange={handleTagChange}
            value={selectedTag}
          >
            {tags.map(tag => (
              <Option key={tag.id} value={tag.id}>{tag.name}</Option>
            ))}
          </Select>
        </Col>
        <Col xs={24} sm={12} lg={4}>
          <Button type="primary">
            批量操作
          </Button>
        </Col>
      </Row>

      <Spin spinning={loading}>
        <Table
          columns={columns}
          dataSource={comments}
          rowKey="id"
          pagination={{
            ...pagination,
            total,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条评论`,
          }}
          onChange={handleTableChange}
        />
      </Spin>
    </Card>
  );
};

export default CommentListPage;
    